package com.kedacom.general.util;

import com.alibaba.fastjson.JSON;
import com.kedacom.general.result.ResponseMessage;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

import java.util.Map;

public class HttpUtils {

    public static ResponseMessage getHttpPostResult(String url, String jsonString, Map<String, String> header) {
        HttpPost post = null;
        HttpResponse response = null;
        try {

            HttpClient httpClient = HttpConnectionPoolUtil.getHttpClient(url);
            post = new HttpPost(url);
            setCommonConfig(post,header);
            post.setEntity(getJsonEntity(jsonString));
            response = httpClient.execute(post);
            String bodyAsString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            return JSON.parseObject(bodyAsString,ResponseMessage.class);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseMessage("服务未知异常,请查看服务启动状态", null,500,"500");
        }finally {
            if(post != null){
                post.releaseConnection();
            }
        }
    }



    private static void setCommonConfig(HttpRequestBase request,Map<String, String> header) {
        RequestConfig requestConfig = RequestConfig.custom()
                //从连接池中获取连接的超时时间
                .setConnectionRequestTimeout(600000)
                //与服务器连接超时时间：httpclient会创建一个异步线程用以创建socket连接，此处设置该socket的连接超时时间
                .setConnectTimeout(600000)
                //socket读数据超时时间：从服务器获取响应数据的超时时间
                .setSocketTimeout(600000).build();
        request.setConfig(requestConfig);
        request.addHeader("Content-type", "application/json; charset=utf-8");
        // 自定义请求头
        if(null != header && !header.isEmpty()){
            for (String head:header.keySet()){
                request.addHeader(head,header.get(head));
            }
        }
    }

    private static StringEntity getJsonEntity(String jsonString) {
        StringEntity entity = new StringEntity(jsonString, Consts.UTF_8);
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        return entity;
    }
}
